<template>
	<view class="page flex flex-direction">
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">巡查历史</block>
		</cu-custom>
		<scroll-view scroll-x class="bg-blue nav text-center">
			<view class="cu-item" :class="item.select?'text-white cur':''" v-for="(item,index) in tabs" :key="index" @tap="clickTap"
			 :data-index="index">
				{{item.title}}
			</view>
		</scroll-view>
		<view class="flex-sub flex flex-direction" v-if="tabs[0].select">
			<view class="flex-sub padding" style="overflow-y: scroll;">
				<view class="cu-list divider radius bg-white shadow padding-lr" v-if="modelMobile.data.length!=0">
					<view class="cu-item padding-tb" v-for="(item,index) in modelMobile.data" :key="index" @tap="clickMobileItem"
					 :data-id="item.id">
						<view class="flex align-center">
							<view class="flex-sub text-lg text-bold text-black">
								{{item.mobileCheckName}}-工程巡检
							</view>
							<view class="cu-tag line-red text-xs" v-if="item.errorCount>0">
								隐患{{item.errorCount}}
							</view>
							<view class="cu-tag line-green text-xs" v-else>
								正常
							</view>
						</view>

						<view class="margin-top-xs">
							开始时间：{{item.patrolStartTime|formatTime}}
						</view>

						<view class="margin-top-xs">
							结束时间：{{item.patrolEndTime|formatTime}}
						</view>

						<view class="margin-top-xs">
							巡检人：{{item.patrolEmployeeName}}
						</view>
					</view>
					
				</view>

				<empty v-if="modelMobile.data.length==0"></empty>
			</view>


			<view class="padding flex flex-direction bg-white">
				<button class="cu-btn bg-blue lg" @tap="clickOpenMobileModel">{{modelMobile.date}}</button>
			</view>
		</view>
		<view class="flex-sub flex flex-direction" v-if="tabs[1].select">

			<view class="flex-sub padding">
				<view class="cu-list radius divider bg-white shadow padding-lr" v-if="modelDevice.data.length!=0">
					<view class="cu-item padding-tb" v-for="(item,index) in modelDevice.data" :key="index" @tap="clickDeviceItem"
					 :data-id="item.id">
						<view class="flex align-center">
							<view class="flex-sub text-lg text-bold text-black">
								{{item.facilityCheckTitle}}-设备巡检
							</view>
							<view class="cu-tag line-red text-xs" v-if="item.errorCount>0">
								隐患{{item.errorCount}}
							</view>
							<view class="cu-tag line-green text-xs" v-else>
								正常
							</view>
						</view>

						<view class="margin-top-xs">
							巡查时间：{{item.patrolTime|formatTime}}
						</view>

						<view class="margin-top-xs">
							巡检人：{{item.patrolEmployeeName}}
						</view>
					</view>
				</view>

				<empty v-if="modelDevice.data.length==0"></empty>
			</view>

			<view class="padding flex flex-direction bg-white">
				<button class="cu-btn bg-blue lg" @tap="clickOpenDeviceModel">
					{{modelDevice.date}}
				</button>
			</view>
		</view>

		<!-- 工程巡检的calendar -->
		<view class="cu-modal bottom-modal" :class="modelMobile.show?'show':''" style="z-index: 10000;">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-red" @tap="clickCloseMobileModel">取消</view>
				</view>
				<view class="">
					<uni-calendar :date="calendar.date" :insert="true" :lunar="false" :start-date="calendar.start" :end-date="calendar.end"
					 @change="onMobileDatePickerChange" :selected="modelMobile.selected"></uni-calendar>
				</view>
			</view>
		</view>

		<!-- 设备巡检的calendar -->
		<view class="cu-modal bottom-modal" :class="modelDevice.show?'show':''" style="z-index: 10000;">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-red" @tap="clickCloseDeviceModel">取消</view>
				</view>
				<view class="">
					<uni-calendar :date="calendar.date" :insert="true" :lunar="false" :start-date="calendar.start" :end-date="calendar.end"
					 @change="onDeviceDatePickerChange" :selected="modelDevice.selected"></uni-calendar>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import api from '../../util/apis/api-patrol.js'
	import ui from '../../util/ui.js'
	import uniCalendar from '@/components/uni-calendar/uni-calendar.vue'
	import empty from '@/components/empty/empty.vue'

	let that = null;


	let request_count = 0;
	let request_current = 0;
	export default {
		components: {
			uniCalendar,
			empty
		},
		filters: {
			formatTime: function(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				month = (month < 10 ? '0' + month : month);
				let day = date.getDate();
				day = (day < 10 ? '0' + day : day);
				let hour = date.getHours();
				hour = (hour < 10 ? '0' + hour : hour);
				let min = date.getMinutes();
				min = (min < 10 ? '0' + min : min);
				let sec = date.getSeconds();
				sec = (sec < 10 ? '0' + sec : sec);
				return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec;
			}
		},
		data() {

			function getFullDateString(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				month = (month < 10 ? '0' + month : month);
				let day = date.getDate();
				day = (day < 10 ? '0' + day : day);
				return year + '-' + month + '-' + day;
			}


			function getToday() {
				let date = new Date();
				return getFullDateString(date.getTime())
			}

			function getBeforeDay() {
				let cur = new Date().getTime();
				let bef = cur - (90 * 24 * 60 * 60 * 1000);
				let date = new Date(bef);
				return getFullDateString(date.getTime());
			}


			return {
				calendar: {
					start: getBeforeDay(),
					end: getToday(),
					date: this.getFullDateString(new Date().getTime())
				},
				tabs: [{
					title: '工程巡检',
					select: true,
					realData: []
				}, {
					title: '设备巡检',
					select: false,
					realData: []
				}],
				modelMobile: {
					show: false,
					date: this.getFullDateString(new Date().getTime()),
					map: new Map(),
					selected: [],
					data: []
				},
				modelDevice: {
					show: false,
					date: this.getFullDateString(new Date().getTime()),
					map: new Map(),
					selected: [],
					data: []
				}
			}
		},
		onLoad() {
			that = this;

			// 获取数据
			that.getAllDate();
		},
		methods: {
			// ———————————————————————————————监听事件—————————————————————————————————
			clickTest: function() {
				// 获取数据
				that.getAllDate();
			},
			/**
			 * 当移动巡检日期发生变化
			 * @param {Object} e
			 */
			onMobileDatePickerChange: function(e) {
				let dateString = e.fulldate;
				that.modelMobile.show = false
				that.modelMobile.date = dateString
				that.refreshMobile(dateString)
			},
			/**
			 * 当设备巡检日期发生变化
			 * @param {Object} e
			 */
			onDeviceDatePickerChange: function(e) {
				let dateString = e.fulldate;
				that.modelDevice.show = false
				that.modelDevice.date = dateString
				that.refreshDevice(dateString)
			},
			// ———————————————————————————————点击事件—————————————————————————————————
			/**
			 * 点击tab的事件
			 */
			clickTap: function(e) {
				let index = e.currentTarget.dataset.index;
				for (let i = 0; i < that.tabs.length; i++) {
					that.tabs[i].select = (i == index);
				}
			},
			/**
			 * 打开移动巡检模态框
			 */
			clickOpenMobileModel: function() {
				that.modelMobile.show = true;
			},
			/**
			 * 关闭移动巡检模态框
			 */
			clickCloseMobileModel: function() {
				that.modelMobile.show = false;
			},
			/**
			 * 打开设备巡检日期模态框
			 */
			clickOpenDeviceModel: function() {
				that.modelDevice.show = true;
			},
			/**
			 * 关闭设备巡检日期选择模态框
			 */
			clickCloseDeviceModel: function() {
				that.modelDevice.show = false;
			},

			/**
			 * 点击移动巡检item的事件
			 * @param {Object} e
			 */
			clickMobileItem: function(e) {
				let id = e.currentTarget.dataset.id;
				uni.navigateTo({
					url: './patrol_history_mobile?id=' + id
				})
			},
			/**
			 * 点击工程巡检item的事件
			 * @param {Object} e
			 */
			clickDeviceItem: function(e) {
				let id = e.currentTarget.dataset.id;
				uni.navigateTo({
					url: './patrol_history_device?id=' + id
				})
			},
			// ———————————————————————————————api方法—————————————————————————————————
			getAllDate: function() {
				let list = [that.getMobileList, that.getDeviceList];
				request_count = list.length;
				request_current = 0;
				ui.showLoading()
				for (let i = 0; i < list.length; i++) {
					list[i]();
				}
			},


			getMobileList: function() {
				let start = (new Date(that.calendar.start)).getTime();
				let end = (new Date(that.calendar.end)).getTime() + 24 * 60 * 60 * 1000;
				api.getMobileHistory(start, end)
					.then(res => {
						that.tabs[0].realData = res;
					})
					.finally(() => {
						that.onCompleted()
					})
			},
			getDeviceList: function() {
				let start = (new Date(that.calendar.start)).getTime();
				let end = (new Date(that.calendar.end)).getTime() + 24 * 60 * 60 * 1000;
				api.getDeviceHistory(start, end)
					.then(res => {
						that.tabs[1].realData = res;
					})
					.finally(() => {
						that.onCompleted()
					});
			},

			onCompleted: function() {
				request_current++;
				if (request_current >= request_count) {
					// 说明请求完成
					ui.hideLoading();
					// 初始化map结构
					for (let i = 0; i < that.tabs[0].realData.length; i++) {
						let mobile = that.tabs[0].realData[i];
						let date = that.transformDate(mobile.patrolStartTime);
						let list = that.modelMobile.map.get(date);
						if (!list || list == null) {
							that.modelMobile.map.set(date, [mobile]);
						} else {
							list.push(mobile)
						}
					}

					for (let i = 0; i < that.tabs[1].realData.length; i++) {
						let device = that.tabs[1].realData[i];
						let date = that.transformDate(device.patrolTime);
						let list = that.modelDevice.map.get(date);
						if (!list || list == null) {
							that.modelDevice.map.set(date, [device]);
						} else {
							list.push(device)
						}
					}

					// 给日历打点
					that.modelMobile.map.forEach(function(value, key) {
						that.modelMobile.selected.push({
							date: key,
							info: '巡'
						})
					});
					that.modelDevice.map.forEach(function(value, key) {
						that.modelDevice.selected.push({
							date: key,
							info: '巡'
						})
					});

					// refresh数据
					that.refreshMobile(that.getFullDateString(new Date().getTime()))
					that.refreshDevice(that.getFullDateString(new Date().getTime()))
				} else {
					request_count = 0;
					request_current = 0;
				}
			},
			// ———————————————————————————————其他方法—————————————————————————————————
			/**
			 * 获取全部时间
			 * 如：2015-06-06
			 * @param {Object} time
			 */
			getFullDateString: function(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				month = (month < 10 ? '0' + month : month);
				let day = date.getDate();
				day = (day < 10 ? '0' + day : day);
				return year + '-' + month + '-' + day;
			},
			/**
			 * 格式化日期,将long类型时间转化为日期
			 * @param {Object} time
			 */
			transformDate: function(time) {
				let date = new Date(time);
				let d = new Date(date.getFullYear(), date.getMonth(), date.getDate());
				return that.getFullDateString(d.getTime());
			},

			/**
			 * 刷新工程巡检列表
			 */
			refreshMobile: function(dateString) {
				let list = that.modelMobile.map.get(dateString);
				if (!list) {
					list = [];
				}
				that.modelMobile.data = list;
			},
			/**
			 * 刷新设备巡检列表
			 */
			refreshDevice: function(dateString) {
				let list = that.modelDevice.map.get(dateString);
				if (!list) {
					list = [];
				}
				that.modelDevice.data = list;
			}
		}
	}
</script>

<style>
	.fixed {
		position: fixed;
		z-index: 99;
	}
</style>
